package com.music.note_android.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.widget.ImageView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.lang.ref.WeakReference

class ThumbnailLoader(private val context: Context) {
    
    private val thumbnailCache = ThumbnailCache.getInstance()
    private val thumbnailGenerator = ThumbnailGenerator(context)
    private val loadingJobs = mutableMapOf<String, Job>()
    
    /**
     * 加载缩略图到ImageView
     * @param noteId 笔记ID
     * @param thumbnailPath 缩略图路径
     * @param dataPath 笔记数据路径（用于生成缩略图）
     * @param imageView 目标ImageView
     * @param placeholderResId 占位符资源ID
     * @param scope 协程作用域
     */
    fun loadThumbnail(
        noteId: String,
        thumbnailPath: String?,
        dataPath: String?,
        imageView: ImageView,
        placeholderResId: Int,
        scope: CoroutineScope
    ) {
        // 取消之前的加载任务
        loadingJobs[noteId]?.cancel()
        
        // 设置占位符
        imageView.setImageResource(placeholderResId)
        
        // 首先尝试从缓存加载
        val cacheKey = getCacheKey(noteId)
        val cachedBitmap = thumbnailCache.getBitmapFromCache(cacheKey)
        if (cachedBitmap != null && !cachedBitmap.isRecycled) {
            imageView.setImageBitmap(cachedBitmap)
            return
        }
        
        // 从文件加载或生成缩略图
        val job = scope.launch {
            val bitmap = loadThumbnailFromFile(noteId, thumbnailPath, dataPath)
            
            withContext(Dispatchers.Main) {
                bitmap?.let {
                    // 检查ImageView是否还有效
                    if (!it.isRecycled) {
                        imageView.setImageBitmap(it)
                        // 添加到缓存
                        thumbnailCache.addBitmapToCache(cacheKey, it)
                    }
                } ?: run {
                    // 加载失败，显示占位符
                    imageView.setImageResource(placeholderResId)
                }
            }
        }
        
        loadingJobs[noteId] = job
    }
    
    /**
     * 预加载缩略图到缓存
     */
    fun preloadThumbnail(
        noteId: String,
        thumbnailPath: String?,
        dataPath: String?,
        scope: CoroutineScope
    ) {
        val cacheKey = getCacheKey(noteId)
        
        // 如果已经在缓存中，直接返回
        if (thumbnailCache.getBitmapFromCache(cacheKey) != null) {
            return
        }
        
        scope.launch {
            val bitmap = loadThumbnailFromFile(noteId, thumbnailPath, dataPath)
            bitmap?.let {
                thumbnailCache.addBitmapToCache(cacheKey, it)
            }
        }
    }
    
    /**
     * 从文件加载缩略图，如果不存在则生成
     */
    private suspend fun loadThumbnailFromFile(
        noteId: String,
        thumbnailPath: String?,
        dataPath: String?
    ): Bitmap? {
        return withContext(Dispatchers.IO) {
            try {
                // 尝试从现有缩略图文件加载
                thumbnailPath?.let { path ->
                    val file = File(path)
                    if (file.exists()) {
                        val bitmap = BitmapFactory.decodeFile(path)
                        if (bitmap != null) {
                            return@withContext bitmap
                        }
                    }
                }
                
                // 如果缩略图不存在，尝试生成新的缩略图
                dataPath?.let { path ->
                    thumbnailGenerator.generateThumbnail(noteId, path)?.let { newThumbnailPath ->
                        return@withContext BitmapFactory.decodeFile(newThumbnailPath)
                    }
                }
                
                null
            } catch (e: Exception) {
                e.printStackTrace()
                null
            }
        }
    }
    
    /**
     * 生成缩略图
     */
    suspend fun generateThumbnail(noteId: String, dataPath: String): String? {
        return thumbnailGenerator.generateThumbnail(noteId, dataPath)
    }
    
    /**
     * 删除缩略图
     */
    suspend fun deleteThumbnail(noteId: String, thumbnailPath: String?) {
        // 从缓存中移除
        val cacheKey = getCacheKey(noteId)
        thumbnailCache.removeBitmapFromCache(cacheKey)
        
        // 删除文件
        thumbnailPath?.let {
            thumbnailGenerator.deleteThumbnail(it)
        }
        
        // 取消加载任务
        loadingJobs[noteId]?.cancel()
        loadingJobs.remove(noteId)
    }
    
    /**
     * 清除所有缓存
     */
    fun clearCache() {
        thumbnailCache.clearCache()
        loadingJobs.values.forEach { it.cancel() }
        loadingJobs.clear()
    }
    
    /**
     * 取消指定笔记的加载任务
     */
    fun cancelLoading(noteId: String) {
        loadingJobs[noteId]?.cancel()
        loadingJobs.remove(noteId)
    }
    
    /**
     * 获取缓存键
     */
    private fun getCacheKey(noteId: String): String {
        return "thumbnail_$noteId"
    }
    
    companion object {
        @Volatile
        private var INSTANCE: ThumbnailLoader? = null
        
        fun getInstance(context: Context): ThumbnailLoader {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: ThumbnailLoader(context.applicationContext).also { INSTANCE = it }
            }
        }
    }
}